<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">权限组管理</span>
    <el-button type="primary" @click="addRole"
               style="float: right;margin-top:10px;">新增权限组
    </el-button>
  </div>

  <!-- 搜索卡片 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="权限组搜索">
        <el-input placeholder="输入名称" style="width: 220px;"
                  v-model="searchRoleData.name"
                  @keydown.enter="loadRoleList"></el-input>
      </el-form-item>
      <el-form-item label="权限组状态" style="width: 290px;">
        <el-select placeholder="请选择状态" v-model="searchRoleData.status">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="-1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadRoleList">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 数据表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="roleListData" v-loading="loading">
      <el-table-column label="ID" prop="id" align="center"></el-table-column>
      <el-table-column label="名称" prop="name" align="center"></el-table-column>
      <el-table-column label="管理员人数" prop="managerCount" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template #default="scope">
          <el-switch active-value="1" inactive-value="-1"
                     @change="changeRoleStatus(scope.row.id)"
                     v-model="scope.row.status"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editRule(scope.row.id,scope.row.name)">分配权限</el-button>
          <el-button link type="primary" @click="editRole(scope.row.id,scope.row)">编辑
          </el-button>
          <el-button link type="danger" @click="deleteRole(scope.row.id,scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页-->
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="handleCurrentChange" style="margin-top: 20px;"/>
  </el-card>

  <!-- 新建权限组弹窗 -->
  <!-- :before-close="handleClose"在弹窗关闭之前调用此自定义函数
   这样避免点击弹窗外部也能将弹窗关闭的问题 -->
  <el-dialog
      :title="dialogTitle"
      style="width: 100vh;padding:40px;"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="名称">
            <el-input placeholder="请输入名称" v-model="saveRoleData.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveRole">保存</el-button>
    </template>
  </el-dialog>

  <!-- 分配权限组弹窗 -->
  <!-- :before-close="handleClose"在弹窗关闭之前调用此自定义函数
   这样避免点击弹窗外部也能将弹窗关闭的问题 -->
  <el-dialog
      :title="dialogRuleTitle"
      style="width: 100vh;padding:40px;"
      v-model="dialogRuleVisible"
      :before-close="handleRuleClose"
      v-loading="allLoad"
  >
    <el-form label-width="80px" label-position="top">
      <div v-for="item in allRuleData">
        <el-form-item :label="item.name">
          <el-checkbox-group v-model="saveRuleData">
            <span v-for="rule in item.children" style="width: 110px;display: inline-block">
              <el-checkbox :label="rule.code" size="large">{{ rule.name }}</el-checkbox>
            </span>
          </el-checkbox-group>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="handleRuleClose">取消</el-button>
      <el-button type="primary" @click="saveRule">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
//权限组列表数据
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "/src/api/axios";

//分页数据
const currentPage = ref(1);//当前页码
const pageSize = ref(15);//每页显示的条数
const totalItems = ref(0);//数据总数

//监听跳转页码的事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadRoleList();
}

//定义加载动画(true为加载,false为加载完成停止加载)
const loading = ref(true)
const allLoad = ref(false)

//列表数据
const roleListData = ref([])

//保存数据
const saveRoleData = ref({});
//弹窗标题
const dialogTitle = ref("新增权限组")

//分配权限标题
const dialogRuleTitle = ref("分配权限")

//要保存的权限组
const saveRuleData = ref([])

const managerRoleList = ref()

//所有权限组
const allRuleData = ref()

const dialogVisible = ref(false)
const dialogRuleVisible = ref(false)

//分配权限
const editRule = (id, name) => {
  saveRoleData.value.id = id;
  allLoad.value = true;
  dialogRuleVisible.value = true;
  dialogRuleTitle.value = dialogRuleTitle.value + '【' + name + '】';

  //获取所有权限
  axios.get('/v1/role/getRules', {serviceName: 'roleService'}).then((response) => {
    allLoad.value = false;
    if (response.data.code === 200) {
      allRuleData.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取权限组权限失败")
    }
  });

  allLoad.value = true;
  //获取该权限组拥有的权限
  axios.get('/v1/role/getRules', {serviceName: 'roleService', params: {id: id}}).then((response) => {
    allLoad.value = false;
    if (response.data.code === 200) {
      saveRuleData.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取权限组权限失败")
    }
  });
};

//分配权限提交
const saveRule = () => {
  saveRoleData.value.rules = JSON.stringify(saveRuleData.value);
  axios.post('/v1/role/updateRule', saveRoleData.value, {serviceName: 'roleService'}).then((response) => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "保存成功");
      handleRuleClose()
      loadRoleList();
    } else {
      ElMessage.error(response.data.msg || "保存失败");
    }
  })
}

//搜索数据
const searchRoleData = ref({})
onMounted(() => {
  loadRoleList();
})

const handleRuleClose = () => {
  dialogRuleVisible.value = false;
  dialogRuleTitle.value = "分配权限";
}

//处理弹窗关闭的方法
const handleClose = () => {
  //用户确认关闭后,关闭弹窗
  dialogVisible.value = false;
  //清空已输入的表单数据
  saveRoleData.value = {};
}

//点击新建的弹窗
const addRole = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增权限组";
}

//加载列表
const loadRoleList = () => {
  loading.value = true;
  searchRoleData.value.page = currentPage.value
  searchRoleData.value.pageNum = pageSize.value
  axios.get('/v1/role/list', {
    serviceName: 'roleService', params: searchRoleData.value
  }).then((response) => {
    if (response.data.code === 200) {
      roleListData.value = response.data.data.records;
      currentPage.value = response.data.data.current;
      totalItems.value = response.data.data.total;
      loading.value = false;
    } else {
      ElMessage.error(response.data.msg || "系统错误")
    }
  })
}

//编辑权限组
const editRole = (id, row) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑权限组";
  saveRoleData.value = row;
};

//删除权限组
const deleteRole = (id, name) => {
  if (confirm("确定要删除【" + name + "】吗？")) {
    axios.post('/v1/role/delete/' + id, {}, {serviceName: 'roleService'}).then((response) => {
      if (response.data.code === 200) {
        ElMessage.success("删除成功");
        loadRoleList();
      } else {
        ElMessage.error(response.data.msg || "删除成功");
      }
    })
  }
};

//更改权限组状态
const changeRoleStatus = (id) => {
  allLoad.value = true;
  axios.post("/v1/role/changeStatus/" + id, {}, {serviceName: "roleService"}).then((response) => {
    allLoad.value = false;
    if (response.data.code === 200) {
      loadRoleList();
    } else {
      ElMessage.error(response.data.msg || "操作失败");
    }
  })
}

//重置搜索方法
const resetSearch = () => {
  searchRoleData.value = {};
  loadRoleList();
}

/**
 * 保存
 */
const saveRole = () => {
  allLoad.value = true;
  axios.post('/v1/role/updateOrInsert', saveRoleData.value, {serviceName: 'roleService'}).then((response) => {
    allLoad.value = false;
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '保存成功');
      dialogVisible.value = false;
      loadRoleList();
    } else {
      ElMessage.error(response.data.msg || "保存失败");
    }
  })

}
</script>

<style scoped>

</style>